import 'package:flutter/material.dart';
import '../resources.dart';

class HRefreshLoadListView extends StatefulWidget {
  final double? refreshWidth;
  final int itemCount;
  final NullableIndexedWidgetBuilder itemBuilder;
  final VoidCallback? onRefresh;
  final VoidCallback? onLoadMore;

  const HRefreshLoadListView({
    super.key,
    this.refreshWidth,
    required this.itemCount,
    required this.itemBuilder,
    this.onRefresh,
    this.onLoadMore,
  });

  @override
  State<StatefulWidget> createState() => _HRefreshLoadListViewState();
}

class _HRefreshLoadListViewState extends State<HRefreshLoadListView> {
  final ScrollController _controller = ScrollController();

  ///上一次的滚动来自于ListView时，需要拦截一次
  bool lastScrollByListView = true;
  bool enableRefresh = true;
  double refreshTop = -100;

  @override
  void initState() {
    super.initState();
    _controller.addListener(scrollListener);
  }

  scrollListener() {
    lastScrollByListView = true;
    if (_controller.position.pixels == _controller.position.maxScrollExtent) {
      enableRefresh = false;
      widget.onLoadMore?.call();
    } else if (_controller.position.pixels == 0) {
      enableRefresh = true;
    } else {
      enableRefresh = false;
    }
  }

  @override
  void dispose() {
    _controller.removeListener(scrollListener);
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Listener(
          onPointerMove: (event) {
            if (enableRefresh) {
              if (lastScrollByListView) {
                lastScrollByListView = false;
                return;
              }
              refreshTop += event.delta.dy;
              if (refreshTop > 0) {
                refreshTop = 0;
              } else if (refreshTop < -100) {
                refreshTop = -100;
              }
              setState(() {});
            }
          },
          onPointerUp: (event) {
            if (refreshTop > -30) {
              widget.onRefresh?.call();
            }
            refreshTop = -100;
            setState(() {});
          },
          child: Container(
            child: widget.itemCount > 0
                ? ListView.builder(
                    shrinkWrap: true,
                    controller: _controller,
                    physics: refreshTop > -100
                        ? const NeverScrollableScrollPhysics()
                        : const ClampingScrollPhysics(),
                    itemCount: widget.itemCount,
                    itemBuilder: widget.itemBuilder)
                : Container(
                    color: Colors.transparent,
                    alignment: Alignment.center,
                    child: assetImage(ImageUtils.no_resources,
                        width: 210.ss, height: 140.ss),
                  ),
          ),
        ),
        AnimatedPositioned(
          duration: const Duration(milliseconds: 200),
          top: refreshTop,
          child: Container(
            width: widget.refreshWidth ?? designWidth.ss,
            height: 100.ss,
            alignment: Alignment.bottomCenter,
            child: AnimatedRotation(
              turns: refreshTop / 50,
              duration: const Duration(milliseconds: 200),
              child: CustomPaint(
                size: const Size(30, 30),
                painter: LoadingProgress(),
              ),
            ),
          ),
        )
      ],
    );
  }
}

class LoadingProgress extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final Rect rect = Rect.fromCircle(
      center: Offset(size.width / 2, size.height / 2), // 圆心
      radius: size.width / 2 - 4, // 半径（减去线条宽度的一半）
    );

    // 绘制阴影
    final Paint shadowPaint = Paint()
      ..color = Colors.black.withOpacity(0.3) // 阴影颜色
      ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 10) // 模糊效果
      ..strokeWidth = 5 // 线条宽度
      ..style = PaintingStyle.stroke; // 描边模式

    canvas.drawArc(
      rect,
      -0.785, // 起始角度（-0.785 弧度 = -45 度）
      4.736, // 扫过的角度（5.236 弧度 = 300 度）
      false, // 是否使用中心点
      shadowPaint,
    );

    // 绘制圆环
    final Paint paint = Paint()
      ..color = ColorUtils.app_color // 设置颜色为主题色
      ..style = PaintingStyle.stroke // 设置为描边模式
      ..strokeWidth = 5 // 设置线条宽度
      ..strokeCap = StrokeCap.round; // 设置圆环两端为圆角

    canvas.drawArc(
      rect,
      -0.785, // 起始角度（-0.785 弧度 = -45 度）
      4.736, // 扫过的角度（5.236 弧度 = 300 度）
      false, // 是否使用中心点
      paint,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
